package com.cloudinnov.logic.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.cloudinnov.dao.EquipmentPointsDao;
import com.cloudinnov.dao.EquipmentsAttrDao;
import com.cloudinnov.dao.EquipmentsDao;
import com.cloudinnov.dao.RealTimeDataDao;
import com.cloudinnov.logic.RealTimeDataLogic;
import com.cloudinnov.model.EquipmentPoints;
import com.cloudinnov.model.Equipments;
import com.cloudinnov.model.EquipmentsAttr;
import com.cloudinnov.model.RealTimeData;
import com.cloudinnov.model.RealTimeObject;
import com.cloudinnov.model.RealtimeList;
import com.cloudinnov.utils.CommonUtils;
import com.cloudinnov.utils.JudgeNullUtil;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;

/**
 * @author chengning
 * @date 2016年2月23日下午2:30:07
 * @email ningcheng@cloudinnov.com
 * @remark
 * @version
 */
@Service("realTimeDataLogic")
public class RealTimeDataLogicImpl extends BaseLogicImpl<RealTimeData> implements RealTimeDataLogic {
	private static final Logger LOG = LoggerFactory.getLogger(RealTimeDataLogic.class);
	private static final String POINT_NAME = "point:";
	private static final String VALUE_NAME = ":value";
	private static final String REALTIME_SPLITTER_LEVEL1 = ",";
	private static final String REALTIME_SPLITTER_LEVEL2 = ";";
	private static final int REALTIME_TIME_LEVEL1 = 0;
	private static final int REALTIME_TIME_OUT_SECOND = 60;
	private static final int REALTIME_TIME_OUT_MILL = 1000;
	@Autowired
	private RealTimeDataDao realTimeDataDao;
	@Autowired
	private JedisPool jedisPool;
	@Autowired
	private EquipmentPointsDao equipmentPointsDao;
	@Autowired
	private EquipmentsDao equipmentDao;
	@Autowired
	private EquipmentsAttrDao equipmentsAttrDao;

	@Override
	public int insertRealtimeList(List<RealTimeData> list, String tableName) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("list", list);
		map.put("tableName", "real_time_data");
		int returnCode = realTimeDataDao.insertRealtimeList(map);
		return returnCode;
	}

	@Override
	public List<RealTimeObject> selectRealtimeDatasByCodes(String[] codes, String language) {
		if (codes == null) {
			return null;
		}
		StringBuilder sb = null;
		Jedis redis = null;
		List<RealTimeObject> realMap = new ArrayList<RealTimeObject>();
		try {
			redis = jedisPool.getResource();
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("language", language);
			map.put("codes", codes);
			Map<String, EquipmentPoints> pointMap = selectPointCodeName(map);
			for (int i = 0; i < codes.length; i++) {
				RealTimeObject rto = new RealTimeObject();
				sb = new StringBuilder();
				sb.append(POINT_NAME).append(codes[i]).append(VALUE_NAME);
				String value = redis.lindex(sb.toString(), 0);
				if (value != null) {
					value = value.replace(" ", "");
					String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
					/**
					 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
					 */
					long timeout = 0L;
					if (valueArray[0].length() > 11) {
						timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0])) / REALTIME_TIME_OUT_MILL;
					} else {
						timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
					}
					if (timeout < REALTIME_TIME_OUT_SECOND) {
						rto.setTimestamps(Long.parseLong(valueArray[0]));
						rto.setValue(Float.parseFloat(valueArray[1]));
					}
				}
				rto.setPointCode(codes[i]);
				rto.setName(pointMap.get(codes[i]).getName());
				if (pointMap.get(codes[i]) != null && pointMap.get(codes[i]).getSysIndexType() != null) {
					rto.setChartType(pointMap.get(codes[i]).getSysIndexType().getChartType());
					rto.setUnit(pointMap.get(codes[i]).getSysIndexType().getUnit());
					rto.setDataType(pointMap.get(codes[i]).getSysIndexType().getDataType());
					rto.setDigits(pointMap.get(codes[i]).getSysIndexType().getDigits());
					rto.setMonitorType(pointMap.get(codes[i]).getSysIndexType().getMonitorType());
				}
				realMap.add(rto);
			}
		} catch (Exception e) {
			LOG.error("method:selectRealtimeDatasByCodes,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return realMap;
	}

	@Override
	public Map<String, Object> selectRealtimeData(String code) {
		if (CommonUtils.isEmpty(code)) {
			return null;
		}
		Jedis redis = null;
		Map<String, Object> realMap = new HashMap<String, Object>();
		try {
			redis = jedisPool.getResource();
			String value = redis.get(code);
			realMap.put("code", code);
			if (value != null) {
				realMap.put("value", redis.get(code).replace(" ", ""));
			} else {
				realMap.put("value", "");
			}
		} catch (Exception e) {
			LOG.error("selectRealtimeData,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return realMap;
	}

	@Override
	public List<EquipmentPoints> selectRealtimeDatasByEquipment(EquipmentPoints equipmentPoint) {
		List<EquipmentPoints> equipmentPoints = equipmentPointsDao.selectListByCondition(equipmentPoint);
		List<EquipmentPoints> values = new ArrayList<EquipmentPoints>();
		if (equipmentPoints != null && equipmentPoints.size() > 0) {
			int size = equipmentPoints.size();
			StringBuilder sb = new StringBuilder();
			for (int i = 0; i < size; i++) {
				sb.append(equipmentPoints.get(i).getCode() + REALTIME_SPLITTER_LEVEL2 + equipmentPoints.get(i).getName()
						+ REALTIME_SPLITTER_LEVEL2);
				if (equipmentPoints.get(i).getType().equals(CommonUtils.POINT_TYPE_MN)) {
					sb.append(equipmentPoints.get(i).getConfig().split("\\|")[0] + REALTIME_SPLITTER_LEVEL2);
					sb.append(equipmentPoints.get(i).getConfig().split("\\|")[2] + REALTIME_SPLITTER_LEVEL2);
					sb.append(equipmentPoints.get(i).getConfig().split("\\|")[4] + REALTIME_SPLITTER_LEVEL2);
				} else if (equipmentPoints.get(i).getType().equals(CommonUtils.POINT_TYPE_SZ)) {
					sb.append("''" + REALTIME_SPLITTER_LEVEL2);
					sb.append("0" + REALTIME_SPLITTER_LEVEL2);
					sb.append("1");
				}
				sb.append(REALTIME_SPLITTER_LEVEL1);
			}
			StringBuilder sbRedis = null;
			Jedis redis = null;
			try {
				redis = jedisPool.getResource();
				String[] codes = sb.toString().split(REALTIME_SPLITTER_LEVEL1);
				EquipmentPoints point = null;
				for (int i = 0; i < codes.length; i++) {
					sbRedis = new StringBuilder();
					sbRedis.append(POINT_NAME).append(codes[i].split(REALTIME_SPLITTER_LEVEL2)[0]).append(VALUE_NAME);
					String value = redis.lindex(sbRedis.toString(), 0);
					point = new EquipmentPoints();
					if (value != null) {
						/**
						 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
						 */
						if (((System.currentTimeMillis() / 1000) - Long.parseLong(value
								.split(REALTIME_SPLITTER_LEVEL1)[REALTIME_TIME_LEVEL1])) < REALTIME_TIME_OUT_SECOND) {
							point.setCode(codes[i].split(REALTIME_SPLITTER_LEVEL2)[0]);
							point.setName(codes[i].split(REALTIME_SPLITTER_LEVEL2)[1]);
							point.setValue(Float.parseFloat(CommonUtils
									.strFormatTwoDecimal(value.replace(" ", "").split(REALTIME_SPLITTER_LEVEL1)[1])));
							point.setUnit(codes[i].split(REALTIME_SPLITTER_LEVEL2)[2]);
							point.setMin(codes[i].split(REALTIME_SPLITTER_LEVEL2)[3]);
							point.setMax(codes[i].split(REALTIME_SPLITTER_LEVEL2)[4]);
							point.setTime(Long.parseLong(value.replace(" ", "").split(REALTIME_SPLITTER_LEVEL1)[0]));
							values.add(point);
						} else {
							point.setCode(codes[i].split(REALTIME_SPLITTER_LEVEL2)[0]);
							point.setName(codes[i].split(REALTIME_SPLITTER_LEVEL2)[1]);
							point.setUnit(codes[i].split(REALTIME_SPLITTER_LEVEL2)[2]);
							point.setMin(codes[i].split(REALTIME_SPLITTER_LEVEL2)[3]);
							point.setMax(codes[i].split(REALTIME_SPLITTER_LEVEL2)[4]);
							values.add(point);
						}
					} else {
						point.setCode(codes[i].split(REALTIME_SPLITTER_LEVEL2)[0]);
						point.setName(codes[i].split(REALTIME_SPLITTER_LEVEL2)[1]);
						point.setUnit(codes[i].split(REALTIME_SPLITTER_LEVEL2)[2]);
						point.setMin(codes[i].split(REALTIME_SPLITTER_LEVEL2)[3]);
						point.setMax(codes[i].split(REALTIME_SPLITTER_LEVEL2)[4]);
						values.add(point);
					}
				}
			} catch (Exception e) {
				LOG.error("selectRealtimeDatasByEquipment,异常\r", e);
			} finally {
				jedisPool.returnResource(redis);
			}
		}
		return values;
	}

	@Override
	public Map<String, EquipmentPoints> selectPointCodeName(Map<String, Object> map) {
		List<EquipmentPoints> pointList = equipmentPointsDao.listByCode(map);
		Map<String, EquipmentPoints> pointMap = new HashMap<String, EquipmentPoints>();
		for (EquipmentPoints point : pointList) {
			pointMap.put(point.getCode(), point);
		}
		return pointMap;
	}

	@Override
	public List<RealtimeList> selectRealtimeDataByPointCode(String code, int type) {
		if (code == null) {
			return null;
		}
		StringBuilder sb = null;
		Jedis redis = null;
		List<RealtimeList> realMap = new ArrayList<RealtimeList>();
		try {
			redis = jedisPool.getResource();
			RealtimeList rto = null;
			sb = new StringBuilder();
			sb.append(POINT_NAME).append(code).append(VALUE_NAME);
			if (type == 1) {
				String value = redis.lindex(sb.toString(), 0);
				rto = new RealtimeList();
				if (value != null) {
					value = value.replace(" ", "");
					String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
					/**
					 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
					 */
					long timeout = 0L;
					if (valueArray[0].length() > 11) {
						timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0])) / REALTIME_TIME_OUT_MILL;
					} else {
						timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
					}
					if (timeout < REALTIME_TIME_OUT_SECOND) {
						String date = CommonUtils.timeStamp2Date(String.valueOf(valueArray[0]), null);
						rto.setName(date);
						List<Object> values = new ArrayList<Object>();
						values.add(date);
						values.add(Float.parseFloat(CommonUtils.strFormatTwoDecimal(valueArray[1])));
						rto.setValue(values);
						realMap.add(rto);
					}
				} else {
					rto.setName(String.valueOf(new Date()));
					realMap.add(rto);
				}
			} else {
				List<String> value = redis.lrange(sb.toString(), 0, 100);
				if (value != null && value.size() > 0) {
					for (String pointValue : value) {
						rto = new RealtimeList();
						pointValue = pointValue.replace(" ", "");
						String[] valueArray = pointValue.split(REALTIME_SPLITTER_LEVEL1);
						/**
						 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
						 */
						long timeout = 0L;
						if (valueArray[0].length() > 11) {
							timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
									/ REALTIME_TIME_OUT_MILL;
						} else {
							timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
						}
						if (timeout < REALTIME_TIME_OUT_SECOND) {
							String date = CommonUtils.timeStamp2Date(String.valueOf(valueArray[0]), null);
							rto.setName(date);
							List<Object> values = new ArrayList<Object>();
							values.add(date);
							values.add(Float.parseFloat(CommonUtils.strFormatTwoDecimal(valueArray[1])));
							rto.setValue(values);
							realMap.add(rto);
						}
					}
				} else {
					rto = new RealtimeList();
					rto.setName(String.valueOf(new Date()));
					realMap.add(rto);
				}
			}
		} catch (Exception e) {
			LOG.error("method:selectRealtimeDatasByCodes,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return realMap;
	}

	@Override
	public double selectPieReportTotalDataByCondition(Map<String, Object> map) {
		double countValue = 0;
		int avgCount = 0;
		StringBuilder sb = null;
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			EquipmentPoints point = new EquipmentPoints();
			point.setLanguage((String) map.get("language"));
			if ((int) map.get("type") == 1) {// 地区
			} else if ((int) map.get("type") == 2) {// 行业
			} else if ((int) map.get("type") == 3) {// 客户
				point.setCustomerCode((String) map.get("customerCode"));
			} else if ((int) map.get("type") == 4) {// 设备
				point.setEquipmentCode((String) map.get("equipmentCode"));
			}
			List<EquipmentPoints> points = equipmentPointsDao.selectListByCondition(point);
			if (points != null && points.size() > 0) {
				for (int i = 0; i < points.size(); i++) {
					sb = new StringBuilder();
					sb.append(POINT_NAME).append(points.get(i).getCode()).append(VALUE_NAME);
					List<String> values = redis.lrange(sb.toString(), 0, -1);
					if ((int) map.get("valueType") == 1) {// 累加值
						for (String redisValue : values) {
							String[] valueArray = redisValue.split(REALTIME_SPLITTER_LEVEL1);
							String time = CommonUtils.timeStampSubStringTen(valueArray[0]);
							String value = valueArray[1];
							String beginTime = CommonUtils.timeStampSubStringTen((String) map.get("beginTime"));
							String endTime = CommonUtils.timeStampSubStringTen((String) map.get("endTime"));
							if (Long.parseLong(time) >= Long.parseLong(beginTime)
									&& Long.parseLong(time) <= Long.parseLong(endTime)) {
								countValue += Double.parseDouble(value);
							}
						}
					} else if ((int) map.get("valueType") == 2) {// 瞬时值 计算平均值
						for (String redisValue : values) {
							String[] valueArray = redisValue.split(REALTIME_SPLITTER_LEVEL1);
							String time = CommonUtils.timeStampSubStringTen(valueArray[0]);
							String value = valueArray[1];
							String beginTime = CommonUtils.timeStampSubStringTen((String) map.get("beginTime"));
							String endTime = CommonUtils.timeStampSubStringTen((String) map.get("endTime"));
							if (Long.parseLong(time) >= Long.parseLong(beginTime) / 1000
									&& Long.parseLong(time) <= Long.parseLong(endTime)) {
								countValue += Double.parseDouble(value);
								avgCount++;
							}
						}
						if (countValue != 0 && avgCount != 0) {
							countValue = countValue / avgCount;
						}
					}
				}
			} else {
				return 0;
			}
		} catch (Exception e) {
			LOG.error("method:selectRealtimeDatasByCodes,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return countValue;
	}

	@Override
	public List<RealTimeObject> selectRealtimeDatasMobile(EquipmentPoints equipmentPoint) {
		List<EquipmentPoints> equipmentPoints = equipmentPointsDao.selectListByCondition(equipmentPoint);
		StringBuilder sb = null;
		Jedis redis = null;
		List<RealTimeObject> realMap = new ArrayList<RealTimeObject>();
		try {
			redis = jedisPool.getResource();
			RealTimeObject rto = null;
			for (int i = 0; i < equipmentPoints.size(); i++) {
				rto = new RealTimeObject();
				rto.setType(equipmentPoints.get(i).getType());
				sb = new StringBuilder();
				sb.append(POINT_NAME).append(equipmentPoints.get(i).getCode()).append(VALUE_NAME);
				String value = redis.lindex(sb.toString(), 0);
				if (value != null) {
					value = value.replace(" ", "");
					String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
					/**
					 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
					 */
					long timeout = 0L;
					if (valueArray[0].length() > 11) {
						timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0])) / REALTIME_TIME_OUT_MILL;
					} else {
						timeout = ((System.currentTimeMillis() / 1000) - Long.parseLong(valueArray[0]));
					}
					if (timeout < REALTIME_TIME_OUT_SECOND) {
						rto.setTimestamps(Long.parseLong(valueArray[0]));
						rto.setValue(Float.parseFloat(valueArray[1]));
					}
				}
				rto.setPointCode(equipmentPoints.get(i).getCode());
				rto.setConfig(equipmentPoints.get(i).getConfig());
				rto.setName(equipmentPoints.get(i).getName());
				realMap.add(rto);
			}
		} catch (Exception e) {
			LOG.error("method:selectRealtimeDatasMobile,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return realMap;
	}

	@Override
	public Map<String, Object> selectReportDataByCondition(Map<String, Object> map) {
		double countValue = 0;
		int avgCount = 0;
		StringBuilder sb = null;
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			EquipmentPoints point = new EquipmentPoints();
			point.setLanguage((String) map.get("language"));
			if ((int) map.get("type") == 1) {// 地区
			} else if ((int) map.get("type") == 2) {// 行业
			} else if ((int) map.get("type") == 3) {// 客户
				point.setCustomerCode((String) map.get("customerCode"));
			} else if ((int) map.get("type") == 4) {// 设备
				point.setEquipmentCode((String) map.get("equipmentCode"));
			}
			List<EquipmentPoints> points = equipmentPointsDao.selectListByCondition(point);
			if (points != null && points.size() > 0) {
				for (int i = 0; i < points.size(); i++) {
					sb = new StringBuilder();
					sb.append(POINT_NAME).append(points.get(i).getCode()).append(VALUE_NAME);
					List<String> values = redis.lrange(sb.toString(), 0, -1);
					if ((int) map.get("valueType") == 1) {// 累加值
						for (String redisValue : values) {
							String[] valueArray = redisValue.split(REALTIME_SPLITTER_LEVEL1);
							String time = CommonUtils.timeStampSubStringTen(valueArray[0]);
							String value = valueArray[1];
							String beginTime = CommonUtils.timeStampSubStringTen((String) map.get("beginTime"));
							String endTime = CommonUtils.timeStampSubStringTen((String) map.get("endTime"));
							String summaryUnit = (String) map.get("summaryUnit");
							switch (summaryUnit) {
							case CustomReportLogicImpl.REPORT_TIME_TYPE_YEAR:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_QUARTER:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_MONTH:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_WEEK:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_DAY:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_HOUR:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_MINUTE:
								break;
							case CustomReportLogicImpl.REPORT_TIME_TYPE_SECOND:
								break;
							}
							if (Long.parseLong(time) >= Long.parseLong(beginTime)
									&& Long.parseLong(time) <= Long.parseLong(endTime)) {
								countValue += Double.parseDouble(value);
							}
						}
					} else if ((int) map.get("valueType") == 2) {// 瞬时值 计算平均值
						for (String redisValue : values) {
							String[] valueArray = redisValue.split(REALTIME_SPLITTER_LEVEL1);
							String time = CommonUtils.timeStampSubStringTen(valueArray[0]);
							String value = valueArray[1];
							String beginTime = CommonUtils.timeStampSubStringTen((String) map.get("beginTime"));
							String endTime = CommonUtils.timeStampSubStringTen((String) map.get("endTime"));
							if (Long.parseLong(time) >= Long.parseLong(beginTime) / 1000
									&& Long.parseLong(time) <= Long.parseLong(endTime)) {
								countValue += Double.parseDouble(value);
								avgCount++;
							}
						}
						if (countValue != 0 && avgCount != 0) {
							countValue = countValue / avgCount;
						}
					}
				}
			} else {
				return map;
			}
		} catch (Exception e) {
			LOG.error("method:selectRealtimeDatasByCodes,异常\r", e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return map;
	}

	@Override
	public Map<String, Object> selectRealtimeIndexTypeDataByEquipment(Equipments model) {
		List<EquipmentPoints> equipmentPoints = equipmentPointsDao.selectPointsByEquCodeAndFeedback(model.getCode(),
				CommonUtils.FEEDBACK_YES);
		Map<String, Object> indexTypeMap = new HashMap<>();
		if (JudgeNullUtil.iList(equipmentPoints)) {
			Jedis redis = null;
			try {
				redis = jedisPool.getResource();
				StringBuilder sb = null;
				String indexType;
				for (int i = 0; i < equipmentPoints.size(); i++) {
					sb = new StringBuilder();
					sb.append(POINT_NAME).append(equipmentPoints.get(i).getCode()).append(VALUE_NAME);
					String value = redis.lindex(sb.toString(), 0);
					if (value != null) {
						value = value.replace(" ", "");
						String[] valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
						/**
						 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
						 */
						long timeout = 0L;
						if (valueArray[0].length() > 11) {
							timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
									/ REALTIME_TIME_OUT_MILL;
						} else {
							timeout = ((System.currentTimeMillis() / 1000L) - Long.parseLong(valueArray[0]));
						}

						if (timeout < REALTIME_TIME_OUT_SECOND) {
							equipmentPoints.get(i).setTime(Long.parseLong(valueArray[0]));
							equipmentPoints.get(i).setValue(Float.parseFloat(valueArray[1]));
						} else {
							equipmentPoints.get(i).setTime(Long.parseLong(valueArray[0]));
							equipmentPoints.get(i).setValue(-1);
						}
					}
					/*
					 * indexTypeMap.put(equipmentPoints.get(i).getIndexType(),
					 * equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue()
					 * : 0);
					 */
					// 如果指标为VI检测器
					indexType = equipmentPoints.get(i).getIndexType();
					if (CommonUtils.isNotEmpty(indexType) && indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_VI)) {
						/*
						 * indexTypeMap.put(indexType, equipmentPoints.get(i).getValue() != null ?
						 * CommonUtils.calculationVI(
						 * Float.parseFloat(String.valueOf(equipmentPoints.get(i).getValue()))) : 0);
						 */
						indexTypeMap.put(indexType,
								equipmentPoints.get(i).getValue() != null
										? String.valueOf(equipmentPoints.get(i).getValue())
										: 0);
					} else if (CommonUtils.isNotEmpty(indexType)
							&& (indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_CO)
									|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_NO2)
									|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_WIND_SPEED)
									|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_ILLUMINATION)
									|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_LIGHT_INTENSITY))) {
						indexTypeMap.put(indexType,
								equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue()
										: "no Data");
					} else {
						indexTypeMap.put(indexType,
								equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue() : -1);
					}
				}
			} catch (JedisException e) {
				LOG.error("selectRealtimeIndexTypeDataByEquipment is error, data : {}, error: {}", model, e);
			} finally {
				jedisPool.returnResource(redis);
			}
		}
		return indexTypeMap;
	}

	/**
     * 设备在线情况websocket方法判断
     */
	@Override
	public List<Equipments> selectRealtimeIndexTypeDataBySectionCode(String sectionCode) {
		long currentTime = System.currentTimeMillis();
		Equipments model = new Equipments();
		model.setSectionCode(sectionCode);
		EquipmentsAttr equAttr = null;
		List<EquipmentsAttr> configList = null;
		List<EquipmentPoints> equipmentPoints = null;
		String value = null;
		StringBuilder sb = null;
		String indexType = null;
		String[] valueArray = null;
		List<Equipments> equipmentList = equipmentDao.selectEquListBySectionCode(model);// 查询路段下的设备
		Jedis redis = null;
		try {
			redis = jedisPool.getResource();
			if (JudgeNullUtil.iList(equipmentList)) {
				Map<String, Object> indexTypeMap = null;
				for (Equipments equipment : equipmentList) {// 遍历查询设备下的点位列表
					boolean isOffline = false;// 离线
					boolean isStop = false;// 停机
					boolean isNormal = false;// 在线
					//先遍历横洞卷帘门设备
					if ("HDJIM".equals(equipment.getCategoryCode())) {
						List<EquipmentPoints> HdjimEquipPoint = equipmentPointsDao.selectPointsByEquCodeAndFeedback(equipment.getCode(),CommonUtils.FEEDBACK_YES);
						if (JudgeNullUtil.iList(HdjimEquipPoint)) {
							indexTypeMap = new HashMap<>();
							for (int i = 0; i < HdjimEquipPoint.size(); i++) {
								sb = new StringBuilder();
								sb.append(POINT_NAME).append(HdjimEquipPoint.get(i).getCode()).append(VALUE_NAME);
								value = new String();
								value = redis.lindex(sb.toString(), 0);
								if (value != null) {
									value = value.replace(" ", "");
									valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
									/**
									 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
									 */
									long timeout = 0L;
									if (valueArray[0].length() > 11) {
										timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
												/ REALTIME_TIME_OUT_MILL;
									} else {
										timeout = ((System.currentTimeMillis() / 1000L) - Long.parseLong(valueArray[0]));
									}

									if (timeout < REALTIME_TIME_OUT_SECOND) {
										HdjimEquipPoint.get(i).setTime(Long.parseLong(valueArray[0]));
										HdjimEquipPoint.get(i).setValue(Float.parseFloat(valueArray[1]));
									} else {
										HdjimEquipPoint.get(i).setTime(Long.parseLong(valueArray[0]));
										HdjimEquipPoint.get(i).setValue(-1);
									}
								}
								indexType = HdjimEquipPoint.get(i).getIndexType();
								indexTypeMap.put(indexType,
										HdjimEquipPoint.get(i).getValue() != null ? HdjimEquipPoint.get(i).getValue()
													: -1);
							}
							// 返回的设备在线的状态
							equipment.setIndexType(indexTypeMap);
							if (JudgeNullUtil.iMap(indexTypeMap)) {
								String indexValue = "";
								for (Object mapValue : indexTypeMap.values()) {
									indexValue = String.valueOf(mapValue);
									if (Double.valueOf(indexValue).intValue() == -1) {
										isOffline = true;
									} else if (Double.valueOf(indexValue).intValue() == 0) {
										isStop = true;
									} else {
										isNormal = true;
									}
								}
								if (isNormal) {// 如果在线
									equipment.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
								} else if (isStop) {// 如果停机
									//本系统没有提及状态,停机即离线
									equipment.setCurrentState(-1);
								} else if (isOffline) {// 如果离线
									equipment.setCurrentState(-1);
								}
							}
						}
					} else { // 再查询其他设备情况,如果在间隔时间之内则查询内存中的数据加快访问速度
						// 或者当前缓存为空
						if (judgementTime(CommonUtils.LAST_VISIT_TIME, currentTime, 300)
								|| CommonUtils.CACHE_EQUIPMENT_ATTRS_MAP.get(equipment.getCode()) == null) {// 此处为超时或缓存中没有值
							equAttr = new EquipmentsAttr();
							equAttr.setEquipmentCode(equipment.getCode());
							configList = equipmentsAttrDao.selectListByCondition(equAttr);
							CommonUtils.CACHE_EQUIPMENT_ATTRS_MAP.put(equipment.getCode(), configList);// 设备附加属性放入内存缓存中便于下次查询
						} else {
							configList = CommonUtils.CACHE_EQUIPMENT_ATTRS_MAP.get(equipment.getCode());// 从内存缓存中获取数据
						}
						if (JudgeNullUtil.iList(configList)) {// 设置附加属性
							equipment.setEquipmentsAttr(configList);
						}
						if (judgementTime(CommonUtils.LAST_VISIT_TIME, currentTime, 300)
								|| CommonUtils.CACHE_EQUIPMENT_POINTS_MAP.get(equipment.getCode()) == null) { // 此处为超时或缓存中没有值
							equipmentPoints = equipmentPointsDao.selectPointsByEquCodeAndFeedback(equipment.getCode(),
									CommonUtils.FEEDBACK_YES);
							CommonUtils.CACHE_EQUIPMENT_POINTS_MAP.put(equipment.getCode(), equipmentPoints);// 设备点位列表放入内存缓存中便于下次查询
						} else {
							equipmentPoints = CommonUtils.CACHE_EQUIPMENT_POINTS_MAP.get(equipment.getCode());// 从内存缓存中获取数据
						}
						if (JudgeNullUtil.iList(equipmentPoints)) {
							indexTypeMap = new HashMap<>();
							for (int i = 0; i < equipmentPoints.size(); i++) {
								sb = new StringBuilder();
								sb.append(POINT_NAME).append(equipmentPoints.get(i).getCode()).append(VALUE_NAME);
								if (equipmentPoints.get(i).getEquipmentCode().equals("EQ2M1YI")) {
									System.err.println("send");
								}
								value = new String();
								value = redis.lindex(sb.toString(), 0);
								if (value != null) {
									value = value.replace(" ", "");
									valueArray = value.split(REALTIME_SPLITTER_LEVEL1);
									/**
									 * 判断实时redis中的第一条数据时间和当前时间相差是否大于60s
									 */
									long timeout = 0L;
									if (valueArray[0].length() > 11) {
										timeout = (System.currentTimeMillis() - Long.parseLong(valueArray[0]))
												/ REALTIME_TIME_OUT_MILL;
									} else {
										timeout = ((System.currentTimeMillis() / 1000L) - Long.parseLong(valueArray[0]));
									}

									if (timeout < REALTIME_TIME_OUT_SECOND) {
										equipmentPoints.get(i).setTime(Long.parseLong(valueArray[0]));
										equipmentPoints.get(i).setValue(Float.parseFloat(valueArray[1]));
									} else {
										equipmentPoints.get(i).setTime(Long.parseLong(valueArray[0]));
										equipmentPoints.get(i).setValue(-1);
									}
								}

								/*
								 * indexTypeMap.put(equipmentPoints.get(i).getIndexType(),
								 * equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue()
								 * : 0);
								 */
								indexType = equipmentPoints.get(i).getIndexType();
								if (CommonUtils.isNotEmpty(indexType) && equipmentPoints.get(i).getIndexType()
										.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_VI)) {
									indexTypeMap.put(indexType, equipmentPoints.get(i).getValue() != null
											? CommonUtils.calculationVI(
													Float.parseFloat(String.valueOf(equipmentPoints.get(i).getValue())))
											: 0);
								} else if (CommonUtils.isNotEmpty(indexType)
										&& (indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_CO)
												|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_NO2)
												|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_WIND_SPEED)
												|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_ILLUMINATION)
												|| indexType.equals(CommonUtils.EQUIPMENTS_INDEXTYPE_LIGHT_INTENSITY))) {
									indexTypeMap.put(indexType,
											equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue()
													: 0);
								} else {
									indexTypeMap.put(indexType,
											equipmentPoints.get(i).getValue() != null ? equipmentPoints.get(i).getValue()
													: -1);
								}
							}
							if (JudgeNullUtil.iMap(indexTypeMap)) {
								String indexValue = "";
								for (Object mapValue : indexTypeMap.values()) {
									indexValue = String.valueOf(mapValue);
									if (Double.valueOf(indexValue).intValue() == -1) {
										isOffline = true;
									} else if (Double.valueOf(indexValue).intValue() == 0) {
										isStop = true;
									} else {
										isNormal = true;
									}
								}
								if (isNormal) {// 如果在线
									equipment.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
								} else if (isStop) {// 如果停机
									equipment.setCurrentState(CommonUtils.EQU_STATE_NORMAL);
								} else if (isOffline) {// 如果离线
									equipment.setCurrentState(-1);
								}
							}
							// 返回的设备在线的状态
							equipment.setIndexType(indexTypeMap);
						}
					}
				}
				CommonUtils.LAST_VISIT_TIME = currentTime;
			}
		} catch (JedisException e) {
			LOG.error("selectRealtimeIndexTypeDataBySectionCode is error, data : {}, error: {}", model, e);
		} finally {
			jedisPool.returnResource(redis);
		}
		return equipmentList;
	}

	/**
	 * judgementTime
	 * 
	 * @param startTime
	 *            13位开始时间戳
	 * @param endtime
	 *            13位结束时间戳
	 * @param intervalTime
	 *            间隔时间(s)
	 * @return true 超出间隔时间 false 在间隔时间之内
	 * @return boolean
	 */
	private boolean judgementTime(long startTime, long endtime, int intervalTime) {
		boolean isTimeout = false;
		if (endtime / 1000 - startTime / 1000 > intervalTime) {
			isTimeout = true;
		}
		return isTimeout;
	}
}
